const db = require("@/db/mysql");
const PublicModel = require("@/common/public.model");
const { TenantContext } = require("@/core/tenant-context");

class UserModel extends PublicModel {
    /**
     * 查询用户列表
     * @param {*} param0 
     * @returns 
     */
    queryUserList({ keyword, page, page_size }) {
        const SQL = `
            SELECT
                u.id, u.username, u.name, u.phone, u.email, u.avatar, u.gender, u.birthday, u.user_type, u.status, u.last_login_time, last_login_ip, 
                s.employee_no, s.department_id, s.position, s.hire_date, s.leave_date, s.id_card, s.address, s.emergency_contact, s.emergency_phone, s.education 
            FROM 
                system_users u LEFT JOIN system_tenant_users ts 
                ON ts.user_id = u.id 
                LEFT JOIN system_staffs s 
                ON u.id = s.user_id 
            WHERE 
                ${keyword ?
                    ` u.name LIKE '%${keyword}%'  
                        OR u.username LIKE '%${keyword}%'  
                        OR u.phone LIKE '%${keyword}%'  
                        OR u.email LIKE '%${keyword}%'  
                        AND 
                    `
                    : '' 
                }
                ts.tenant_id = '${TenantContext.getCurrentTenant()}' 
                AND u.is_delete = 0 
                AND ts.is_delete = 0 
            LIMIT ${this.pageLimit(page_size, page)}
        `;
        return this.query(SQL);
    }

    /**
     * 查询用户列表
     * @param {*} param0 
     * @returns 
     */
    queryUserListTotal({ keyword }) {
        const SQL = `
            SELECT
               count(u.id) as count 
            FROM 
                system_users u LEFT JOIN system_tenant_users ts 
                ON ts.user_id = u.id 
                LEFT JOIN system_staffs s 
                ON u.id = s.user_id 
            WHERE 
                ${keyword ?
                    ` u.name LIKE '%${keyword}%'  
                        OR u.username LIKE '%${keyword}%'  
                        OR u.phone LIKE '%${keyword}%'  
                        OR u.email LIKE '%${keyword}%'  
                        AND 
                    `
                    : '' 
                }
                ts.tenant_id = '${TenantContext.getCurrentTenant()}' 
                AND u.is_delete = 0 
                AND ts.is_delete = 0 
        `;
        return this.query(SQL);
    }
    /**
     * 创建用户
     * @param {*} data 
     * @returns 
     */
    createUser(data) {
        return this.create({ table: 'system_users', data, result: true, isNotTenant: true });
    }

    /**
     * 创建租户下的用户
     * @param {*} data 
     * @returns 
     */
    createTenantUser(data) {
        return this.create({ table: 'system_tenant_users', data, result: true });
    }

    /**
     * 创建员工
     * @param {*} data 
     * @returns 
     */
    createStaff(data) {
        return this.create({ table: 'system_staffs', data, result: true });
    }

    /**
     * 创建店铺
     * @param {*} data 
     * @returns 
     */
    createShop(data) {
        return this.create({ table: 'shops', data, result: true });
    }

    /**
     * 修改店铺
     * @param {*} data 
     * @returns 
     */
    updateShop(id, data) {
        return this.updateById({ table: 'shops', data, id, result: true });
    }

    /**
     * 查询用户租户列表
     * @param {*} param0 
     * @returns 
     */
    queryTenantListByUserId({ user_id } = {}) {
        const SQL = `
            SELECT
                t.id,
                t.name,
                t.code,
                t.contact_person,
                t.contact_phone,
                t.description,
                t.status,
                t.expire_time
            FROM
                system_tenant_users tu
                LEFT JOIN system_tenants t ON tu.tenant_id = t.id
            WHERE
                tu.user_id = '${user_id || TenantContext.getCurrentUser()}'
                AND t.is_delete = 0
        `;
        return this.query(SQL);
    }

    /**
     * 设置用户租户
     * @param {*} param0 
     */
    setUserTenants({ uid, tenants, role_code }) {
        const data = tenants.map(tenant_id => {
            return {
                tenant_id: tenant_id,
                user_id: uid,
                role_code: role_code || 'system_super_admin'
            }
        })
        return this.createMultiple({ table: 'system_tenant_users', data, result: true, isNotTenant: true })
    }

    // 设置头像昵称
    setAvatarNickName({ avatar, nickName, openid }) {
        const SQL = this.sql(`
        UPDATE 
            system_account 
        SET 
            nick_name = '${nickName}'
            ${avatar ? `, avatar_image = '${avatar}' ` : ''} 
        WHERE 
            wx_openid = '${openid}'
        `);
        return db.query(SQL);
    }

    /**
     * 设置用户到某个群组
     * @param {*} param0 
     */
    setUserFamilyGroup({ user_id, gid }) {
        const SQL = `
            INSERT INTO
                family_group_members (
                    id, user_id, group_id
                )
            VALUE (
                '${this.id}', '${user_id}', '${gid}'
            )
        `;
        return this.query(SQL);
    }

    /**
     * 用户id查询用户所有家庭组
     * @param {*} param0 
     */
    getFamilyIdListByUserId({ uid }) {
        const SQL = `
            SELECT DISTINCT
                group_id
            FROM family_group_members
            WHERE
                user_id = '${uid}'
        `;
        return this.query(SQL)
    }
}

module.exports = new UserModel();
